// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import qs from 'qs';
import 'babel-polyfill' //  支持ie浏览
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
import store from './store/index'

// 引入高德地图

import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
    key: 'your amap key',
    plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor'],
    // 默认高德 sdk 版本为 1.4.4
    v: '1.4.4'
});

//md5方法
import crypto from 'crypto';
Vue.prototype.$md5 = function (n) {
  let md5 = crypto.createHash("md5");
  md5.update(n);
  return md5.digest('hex');
}

// 图片前缀的全局变量
// global.img_url="http://192.168.0.133:8000/";   //内网
// global.img_url="http://47.106.35.90:8000/"; //外网
global.img_url="https://www.jtgcgj.com/";

// 限制文件上传大小  10m以内，超过10m 阻止上传动作 给与对应提示
Vue.prototype.BeforeUploadFn = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    this.$message.error('上传文件大小不能超过 10MB!');
  }
  return isLt10M;
}

// 引入Echarts
import Echarts from 'echarts'
Vue.prototype.echarts = Echarts
Vue.use(Echarts)

//引入elementui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import '@/assets/css/element-variables.scss'
// import '../theme/index.css';
import '@/assets/css/common.css';
import "@/assets/font/iconfont.css";
Vue.use(ElementUI);

Vue.config.productionTip = false

//引入axios
axios.defaults.withCredentials = true
Vue.prototype.$axios = axios

//分页函数
Vue.prototype.SizeChange = function(val, f1, currentPage, pageSize) {
    console.log(`每页 ${val} 条`);
    this.pageSize = val;
    f1(currentPage, pageSize);

}
Vue.prototype.CurrentChange = function(val, f1, currentPage, pageSize) {
    console.log(`当前页: ${val}`);
    this.currentPage = val;
    f1(currentPage, pageSize);
}

// startLOading,endLoading
let loading //定义loading变量
let needLoadingRequestCount = 0
Vue.prototype.startLoading = function() { //使用Element loading-start 方法
        if (needLoadingRequestCount === 0) {
            loading = this.$loading({
                lock: true,
                text: '正在加载，请勿刷新！',
                background: 'rgba(247,247,247, 0.2)'
            })
        }
        needLoadingRequestCount++
    }
    //切换页面的时候取消所有的路由
Vue.prototype.endLoading = function() { //使用Element loading-close 方法
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        if (loading) loading.close()
    }
}

// 封装ajax请求
  Vue.prototype.$https = function(param) {
    axios.defaults.headers.common['token'] = localStorage.getItem("token");
        this.startLoading();
        if (param.methods == 'post') {
            this.$axios.post(param.url, qs.parse(param.data)).then((res) => {
               this.endLoading();
                if (res.data.flag == 1) {
                    typeof param.success === 'function' && param.success(res);
                } else if (res.data.flag == 0) {
                    this.$message({
                      message:res.data.message || res.data.msg,
                      type:'error',
                    })
                    typeof param.error === 'function' && param.error(res);
                } else if (res.data.flag == 2) {
                  localStorage.clear();
                  this.$router.replace('/index')
                }
            }).catch(res => {
              console.log(res)
              this.endLoading()
              this.$message({
                message:'网络异常，请稍后再试！',
                type:'error',
                duration:500
              })
              // this.$message.error("网络异常，请稍后再试！")
            })
        }
        if (param.methods == 'get') {
            this.$axios.get(param.url, { params: param.data }).then((res) => {
                this.endLoading()
                if (res.data.flag == 1) {
                  typeof param.success === 'function' && param.success(res);
                } else if (res.data.flag == 0) {
                  this.$message({
                    message:res.data.message || res.data.msg,
                    type:'error',
                  })
                  typeof param.error === 'function' && param.error(res);
                } else if (res.data.flag == 2) {
                  localStorage.clear();
                  this.$router.replace('/index')
                }
            }).catch(res => {
              this.endLoading()
              this.$message({
                message:'网络异常，请稍后再试！',
                type:'error',
                duration:500
              })
              // this.$message.error("网络异常，请稍后再试！")
            })
        }
    }
//时间过滤器
import * as filters from '@/components/common/js/filter.js'
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key])
})

//深拷贝
Vue.prototype.deepClone = function(obj) {
  let newObj;
  if (Array.isArray(obj)) {
    newObj = [];
  } else if (typeof obj === 'object') {
    newObj = {};
  } else {
    newObj = obj;
  };
  if (typeof obj === 'object') {
    for (let item in obj) {
      if(obj.hasOwnProperty(item)) {
        if(obj[item] && typeof obj[item] === 'object') {
          newObj[item] = this.deepClone(obj[item])
        } else {
          newObj[item] = obj[item]
        }
      }
    }
  }
  return newObj;
}

// 消息提示
Vue.prototype.$msg = function(msg){
    this.$message({
      dangerouslyUseHTMLString:true,
        message:`
        <div>
          <img src="../static/msg/success.png" style="display:block;width:50px;height:50px;margin:10px auto;">
        </div>
        <div>
          <span style="font-size:16px;color:#666;font-weight:600;">${msg}</span>
        </div>
        `,
        type:"",
        center:true,
        customClass:"msgClass",
        duration:1500
    })
}

// 消息提示
Vue.prototype.$erMsg = function(msg){
  this.$message({
    dangerouslyUseHTMLString:true,
      message:`
      <div>
        <img src="../static/msg/error.png" style="display:block;width:50px;height:50px;margin:10px auto;">
      </div>
      <div>
        <span style="font-size:16px;color:#666;font-weight:600;">${msg}</span>
      </div>
      `,
      type:"",
      center:true,
      customClass:"msgClass",
      duration:1500
  })
}

//路由错误
router.onError((err) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = err.message.match(pattern);
  if (isChunkLoadFailed) {
    let chunkBool = sessionStorage.getItem('chunkError');
    let nowTimes = Date.now();
    if (chunkBool === null || chunkBool && nowTimes - parseInt(chunkBool) > 60000) {//路由跳转报错,href手动跳转
      sessionStorage.setItem('chunkError', 'reload');
      const targetPath = routers.history.pending.fullPath;
      window.location.href = window.location.origin + targetPath;
    }else if(chunkBool === 'reload'){ //手动跳转后依然报错,强制刷新
      sessionStorage.setItem('chunkError', Date.now());
      window.location.reload(true);
    }
  }
})
//路由拦截
const whiteList = ['/login'] // 路由白名单
router.beforeEach((to, from, next) => {
  const role = localStorage.getItem('ms_username');
  if (whiteList.indexOf(to.path) !== -1){
    next();
  }else{
    if (!role && to.path !== '/index') {
      next('/index');
    } else if (to.meta.permission) {
      next();
    } else {
      if (navigator.userAgent.indexOf('MSIE') > -1) {
        Vue.prototype.$alert('请使用更高版本的浏览器查看', '浏览器不兼容通知', {
          confirmButtonText: '确定'
        });
      } else {
        next();
      }
    }
  }

})

// 禁止控制台打印
if(!global.consoleSwitch){
  console.log = ()=>{}
}

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})
